package models

import (
	"ginadmin/db"
	"github.com/jinzhu/gorm"
)

type User struct {
	gorm.Model
	Name     string
	UserName string
	Password string
	Status   int32
	Role     string
	Roleid   uint
	ErrorNum int32 //密码错误次数
	Phone    string
	Rem      string
	OrgId    uint
}

func (m *User) Dels(ids string) error {
	err := new(error)
	DB := db.GetInstance().GetDB()
	if *err = DB.Unscoped().Delete(m, "id in ("+ids+")").Error; err != nil {
		return *err
	}
	return *err
}

func (m *User) Add() (uint, error) {
	err := new(error)
	DB := db.GetInstance().GetDB()
	if *err = DB.Create(m).Error; err != nil {
		return 0, *err
	}
	return m.ID, *err
}

func (a *User) FindByUsername(username string) error {
	DB := db.GetInstance().GetDB()
	err := DB.Where("user_name=?", username).Find(&a).Error
	return err
}

func (a *User) FindById(userid uint) error {
	DB := db.GetInstance().GetDB()
	err := DB.Where("id=?", userid).Find(&a).Error
	return err
}

func (a *User) UpdatePwd(userid uint, pwd string) error {
	DB := db.GetInstance().GetDB()
	err := DB.Where("id=?", userid).Model(&a).Update("password", pwd).Error
	return err
}

func (m *User) ErrorPwd() error {
	DB := db.GetInstance().GetDB()
	return DB.Model(&m).Update("errornum", m.ErrorNum+1).Error
}

//登录成功之后将错误密码置为0
func (m *User) LoginSucc() error {
	DB := db.GetInstance().GetDB()
	return DB.Model(&m).Update("errornum", 0).Error
}

func UserList() (user []User, err error) {
	DB := db.GetInstance().GetDB()
	err = DB.Find(&user).Error
	if err != nil {
		return user, err
	}
	return user, err
}
